package com.weslide.weslideapp.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.json.JSONException;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.KeyguardManager.OnKeyguardExitResult;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fima.glowpadview.GlowPadView;
import com.fima.glowpadview.GlowPadView.OnTriggerListener;
import com.gt.cl.http.CLConnectionException;
import com.gt.cl.http.CLInvalidNetworkException;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.weslide.weslideapp.R;
import com.weslide.weslideapp.fragment.ScoreStoreFragment;
import com.weslide.weslideapp.manager.api.APIManager;
import com.weslide.weslideapp.manager.api.LoginManager;
import com.weslide.weslideapp.pojo.ao.AddScoreAO;
import com.weslide.weslideapp.pojo.ao.AdverImgListAO;
import com.weslide.weslideapp.pojo.ao.AdverimgsAO;
import com.weslide.weslideapp.pojo.ao.LoginAO;
import com.weslide.weslideapp.util.TMTPAsyncTask;

public class UnlockActivity extends WeSlideActivity implements
		OnTriggerListener {
	private static final String TAG = "UnlockActivity";
	private GlowPadView mGlowPadView;
	private TMTPAsyncTask<Void, Void, Void> addScoreAsyncTask;
	private AddScoreAO addScoreAO;
	private TextView mTvAddScoreRight;
	private TextView mTvAddScoreLeft;
	private TMTPAsyncTask<Void, Void, Void> asyncTask;
	private AdverImgListAO adverImgListAO;
	private List<AdverimgsAO> adverImgList = new ArrayList<AdverimgsAO>();
	private int currentAdverImgIndex = 0;
	private DisplayImageOptions options;
	private ImageView mImgVBG;

	private boolean isRight = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置无标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 设置全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.page_unlock);
		disableSystemLock();
		// --------------------------------------
		mGlowPadView = (GlowPadView) findViewById(R.id.glow_pad_view);
		mImgVBG = (ImageView) findViewById(R.id.page_unlock_mImgVBG);
		mGlowPadView.setOnTriggerListener(this);
		mTvAddScoreRight = (TextView) findViewById(R.id.page_unlock_mTvAddScoreRight);
		mTvAddScoreLeft = (TextView) findViewById(R.id.page_unlock_mTvAddScoreLeft);
		// uncomment this to make sure the glowpad doesn't vibrate on touch
		// mGlowPadView.setVibrateEnabled(false);

		// uncomment this to hide targets
		// mGlowPadView.setShowTargetsOnIdle(true);
		initAdverImages();
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.bg3)
				.showImageForEmptyUri(R.drawable.bg3)
				.showImageOnFail(R.drawable.bg3).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.ARGB_8888).build();
	}

	public void disableSystemLock() {
		KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
		String lockTag = getLocalClassName();
		Log.i(TAG, "lockTag >>> " + lockTag);
		final KeyguardManager.KeyguardLock keyguardLock = keyguardManager
				.newKeyguardLock(lockTag);
		KeyguardManager.OnKeyguardExitResult onKeyguardExitResult = new OnKeyguardExitResult() {

			@Override
			public void onKeyguardExitResult(boolean success) {
				if (success) {
					Log.i(TAG, "success");
				} else {
					Log.i(TAG, "fail");
				}
			}
		};
		keyguardManager.exitKeyguardSecurely(onKeyguardExitResult);
		keyguardLock.disableKeyguard();
	}

	private void initAdverImages() {
		asyncTask = new TMTPAsyncTask<Void, Void, Void>(this) {

			@Override
			protected void doOnSuccess(Void result) {
				if (adverImgListAO.getStatus().equals("1")) {
					adverImgList.addAll(adverImgListAO.getAdverImgList());
					loadImage();
				}
				for (int i = 0; i < adverImgList.size(); i++) {
					Log.i("Unlock", "name >>>>" + adverImgList.get(i).getName());
				}

			}

			@Override
			protected Void doInBackground(Void params)
					throws CLInvalidNetworkException, CLConnectionException {
				LoginAO userInformation = LoginManager.getInstance()
						.getUserInformation();

				try {
					adverImgListAO = APIManager.getInstance().getAdverImgs(
							userInformation.getUserId());
					Log.i("Unlock", "size >>> "
							+ adverImgListAO.getAdverImgList().size());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return null;
			}
		};
		asyncTask.execute();
	}

	private void loadImage() {
		Log.i("UnlockActivity", "size >>> " + adverImgList.size());
		currentAdverImgIndex = new Random().nextInt(adverImgList.size());
		ImageLoader.getInstance().displayImage(
				adverImgList.get(currentAdverImgIndex).getAdverImgUrls(),
				mImgVBG, options);
		Log.i("Unlock", "ImageUrl >>> "
				+ adverImgList.get(currentAdverImgIndex).getAdverImgUrls());

		Log.i("UnlockActivity", "currentAdverImgIndex >>> "
				+ currentAdverImgIndex);
	}

	@Override
	public void onGrabbed(View v, int handle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReleased(View v, int handle) {
		mGlowPadView.ping();

	}

	@Override
	public void onTrigger(View v, int target) {

		final int resId = mGlowPadView.getResourceIdForTarget(target);
		switch (resId) {
		case R.drawable.ic_item_unlock:
			isRight = true;
			addScore();
			// mTvAddScore.setVisibility(View.VISIBLE);
			//
			// ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 1.0f,
			// 2.0f, 2.0f);
			// scaleAnimation.setDuration(1500);
			// mTvAddScore.startAnimation(scaleAnimation);
			// unLock();
			break;

		case R.drawable.ic_item_detail:
			if (LoginManager.getInstance().isUserLogined()) {
				Intent intent = new Intent(UnlockActivity.this,
						GiftDetailActivity.class);
				intent.putExtra(GiftDetailActivity.EXTRA_GOODID, adverImgList
						.get(currentAdverImgIndex).getGoodId());
				finish();
				startActivity(intent);
			} else {
				Intent intent = new Intent(UnlockActivity.this,
						MainActivity_de.class);
				finish();
				startActivity(intent);
			}

			break;
		case R.drawable.ic_item_website:
			isRight = false;
			addScore();

			break;
		}

	}

	private void unLock() {
		// Intent intent = new Intent();
		// intent.setClass(UnlockActivity.this, MainActivity_de.class);
		finish();
		// startActivity(intent);
	}

	private void addScore() {
		addScoreAsyncTask = new TMTPAsyncTask<Void, Void, Void>(this, false) {

			@Override
			protected void doOnSuccess(Void result) {
				LoginManager.getInstance().updateScore(
						addScoreAO.getTotalScore());
				Log.i("UnlockActivity", "score >>> " + addScoreAO.getScore());

				Animation loadAnimation = AnimationUtils.loadAnimation(
						UnlockActivity.this, R.anim.add_score_anim);
				// ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f,
				// 1.0f,
				// 2.0f, 2.0f);
				loadAnimation.setDuration(2000);
				loadAnimation.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {

					}

					@Override
					public void onAnimationRepeat(Animation animation) {

					}

					@Override
					public void onAnimationEnd(Animation animation) {
						disableSystemLock();
						if (isRight) {
							mTvAddScoreRight.setVisibility(View.GONE);
							unLock();
						} else {
							mTvAddScoreLeft.setVisibility(View.GONE);
							toWebSite();
						}

					}
				});
				if (isRight) {
					mTvAddScoreRight.setText("+" + addScoreAO.getScore());
					mTvAddScoreRight.setVisibility(View.VISIBLE);
					mTvAddScoreRight.startAnimation(loadAnimation);
					// findViewById(R.id.page_unlock_mLlAddScore).startAnimation(
					// loadAnimation);
				} else {
					mTvAddScoreLeft.setText("+" + addScoreAO.getScore());
					mTvAddScoreLeft.setVisibility(View.VISIBLE);
					mTvAddScoreLeft.startAnimation(loadAnimation);
				}

				// unLock();
			}

			@Override
			protected Void doInBackground(Void params)
					throws CLInvalidNetworkException, CLConnectionException {
				LoginAO userInformation = LoginManager.getInstance()
						.getUserInformation();

				try {
					addScoreAO = APIManager.getInstance().addScore(
							userInformation.getUserId());
				} catch (JSONException e) {
					e.printStackTrace();
				}

				return null;
			}
		};

		addScoreAsyncTask.execute();
	}

	private void toWebSite() {
		Intent intent = new Intent(this, WebSiteActivity.class);
		intent.putExtra("url", adverImgList.get(currentAdverImgIndex).getUrl());
		finish();
		startActivity(intent);
	}

	@Override
	public void onGrabbedStateChange(View v, int handle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFinishFinalAnimation() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		return true;
	}
}
